import type router from './router'
import { useinfo } from '@/store/userinfo'
import { upLine } from '@/socket/index'
const whiteRouters = ['/login', '/404', '/register']
// import axios from 'axios'
import { getUserInfo } from '@/api/users'
export default function (road: typeof router) {
  road.beforeEach((to, from, next) => {
    // 如果前往路由非白名单路由则验证token是否存在
    const token = localStorage.getItem('token');
    if (!whiteRouters.includes(to.path)) {
      // 如果没有token重定向到登录
      if (!token) {
        return next('/login')
      } else {
        getUserInfo().then(res => {
              useinfo.value = res.data //存储用户信息
              upLine(res.data.useinfo)  // 通知服务器当前登入者的id
          next()
        }).catch(() => {
           next('/login');
        })
        // axios({
        //   url: '/api-server/users/profile',
        //   method: 'get',
        //   headers: {
        //     Authorization: `Bearer ${token}`
        //   }
        // }).then(res => {
        //   const { code } = res.data
        //   console.log(222222)
        //   if (code !== 200) return next('/login');
        //   next()
        // })
        // console.log(11111111);
        return
      }
    }
    next()
  })
}
